﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using XXF.Api;
using Newtonsoft.Json;

namespace XXF.BasicService.NotifyCenter
{
    /// <summary>
    /// 消息中心
    /// </summary>
    public class NotifyCenterProvider
    {
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="templateNo">模板编号</param>
        /// <param name="parameters">参数</param>
        /// <param name="customerInfo">客户联系信息</param>
        /// <returns></returns>
        public NCResult SendMessage(string templateNo, Dictionary<string, string> parameters, NCCustomerInfo customerInfo, string yhzh)
        {
            try
            {
                string PostUrl = NCConfig.ApiUrl + "/NotifyCenter/SendMessage";
                templateNo = System.Web.HttpUtility.UrlEncode(templateNo);
                string paramersStr = "";
                string customerInfoStr = "";
                string yhzhStr = "";
                if (parameters != null)
                {
                    paramersStr = this.GetParameters(parameters);
                }
                if (customerInfo != null)
                {
                    customerInfoStr = this.GetCustomerInfo(customerInfo);
                }
                paramersStr = System.Web.HttpUtility.UrlEncode(paramersStr);
                customerInfoStr = System.Web.HttpUtility.UrlEncode(customerInfoStr);
                yhzhStr = System.Web.HttpUtility.UrlEncode(yhzh);
                string postStrTpl = "templateNo={0}&parameters={1}&customerInfo={2}&userID={3}";
                string paraurl = string.Format(postStrTpl, templateNo, paramersStr, customerInfoStr, yhzhStr);
                return this.Post(PostUrl, paraurl);
            }
            catch
            {
                return new NCResult { code = -1, msg = "内部服务器错误" };
            }
        }

        /// <summary>
        /// 批量发送信息
        /// </summary>
        /// <param name="templateNo">模板编号</param>
        /// <param name="parameters">参数</param>
        /// <param name="customerInfo">客户联系信息</param>
        /// <returns></returns>
        public NCResult SendMessage(string templateNo, Dictionary<string, string> parameters, List<NCCustomerInfo> customerInfos, string yhzhs)
        {
            try
            {
                string PostUrl = NCConfig.ApiUrl + "/NotifyCenter/SendMessageBatch";
                templateNo = System.Web.HttpUtility.UrlEncode(templateNo);
                string paramersStr = "";
                string customerInfoStr = "";
                string yhzhStr = "";
                if (parameters != null) 
                {
                    paramersStr = this.GetParameters(parameters);
                }
                if (customerInfos != null)
                {
                    customerInfoStr = this.GetCustomerInfos(customerInfos);
                }
                paramersStr = System.Web.HttpUtility.UrlEncode(paramersStr);
                customerInfoStr = System.Web.HttpUtility.UrlEncode(customerInfoStr);
                yhzhStr = System.Web.HttpUtility.UrlEncode(yhzhs);
                string postStrTpl = "templateNo={0}&parameters={1}&customerInfos={2}&userIDs={3}";
                string paraurl = string.Format(postStrTpl, templateNo, paramersStr, customerInfoStr, yhzhStr);
                return this.Post(PostUrl, paraurl);
            }
            catch(Exception ex)
            {
                return new NCResult { code = -1, msg = ex.Message };
            }
        }

        /// <summary>
        /// 批量推送消息
        /// </summary>
        /// <param name="templateNo"></param>
        /// <param name="parameters"></param>
        /// <param name="customerInfo"></param>
        /// <returns></returns>
        public NCResult BatchSendMessage(string templateNo, Dictionary<string, string> parameters, NCCustomerInfo customerInfo)
        {
            try
            {
                string PostUrl = NCConfig.ApiUrl + "/NotifyCenter/SendMessage";
                templateNo = System.Web.HttpUtility.UrlEncode(templateNo);
                string paramersStr = "";
                string customerInfoStr = "";
                string yhzhStr = "";
                if (parameters != null)
                {
                    paramersStr = this.GetParameters(parameters);
                }
                if (customerInfo != null)
                {
                    customerInfoStr = this.GetCustomerInfo(customerInfo);
                }
                paramersStr = System.Web.HttpUtility.UrlEncode(paramersStr);
                customerInfoStr = System.Web.HttpUtility.UrlEncode(customerInfoStr);
                yhzhStr = System.Web.HttpUtility.UrlEncode("batch");
                string channel = System.Web.HttpUtility.UrlEncode("1");
                string postStrTpl = "templateNo={0}&parameters={1}&customerInfo={2}&userID={3}&channel={4}";
                string paraurl = string.Format(postStrTpl, templateNo, paramersStr, customerInfoStr, yhzhStr);
                return this.Post(PostUrl, paraurl);
            }
            catch
            {
                return new NCResult { code = -1, msg = "内部服务器错误" };
            }
        }

        /// <summary>
        /// 获取用户的消息列表
        /// </summary>
        /// <param name="yhzh"></param>
        /// <param name="pageNo"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public NCResult ListNotifys(string yhzh, int pageNo, int pageSize)
        {
            string PostUrl = NCConfig.ApiUrl + "/NotifyCenter/ListNotifys";
            string userID = System.Web.HttpUtility.UrlEncode(yhzh);
            string pageNoStr = System.Web.HttpUtility.UrlEncode(pageNo.ToString());
            string pageSizeStr = System.Web.HttpUtility.UrlEncode(pageSize.ToString());
            string postStrTpl = "userID={0}&pageNo={1}&pageSize={2}";
            string paraurl = string.Format(postStrTpl, userID, pageNoStr, pageSizeStr);
            return this.Post(PostUrl, paraurl);
        }

        /// <summary>
        /// 标记消息为清除
        /// </summary>
        /// <param name="yhzh"></param>
        /// <param name="queueID"></param>
        /// <returns></returns>
        public NCResult SignDelete(string yhzh, long queueID)
        {
            string PostUrl = NCConfig.ApiUrl + "/NotifyCenter/SignDelete";
            string userID = System.Web.HttpUtility.UrlEncode(yhzh);
            string queueIDStr = System.Web.HttpUtility.UrlEncode(queueID.ToString());
            string postStrTpl = "userID={0}&queueID={1}";
            string paraurl = string.Format(postStrTpl, userID, queueIDStr);
            return this.Post(PostUrl, paraurl);
        }

        /// <summary>
        /// 标记消息为清除 批量
        /// </summary>
        /// <param name="yhzh"></param>
        /// <param name="queueID"></param>
        /// <returns></returns>
        public NCResult SignDelete(string yhzh, string queueID)
        {
            string PostUrl = NCConfig.ApiUrl + "/NotifyCenter/SignDelete";
            string userID = System.Web.HttpUtility.UrlEncode(yhzh);
            string queueIDStr = System.Web.HttpUtility.UrlEncode(queueID.ToString());
            string postStrTpl = "userID={0}&queueID={1}";
            string paraurl = string.Format(postStrTpl, userID, queueIDStr);
            return this.Post(PostUrl, paraurl);
        }

        /// <summary>
        /// 标记消息为已读
        /// </summary>
        /// <param name="yhzh"></param>
        /// <param name="queueID"></param>
        /// <returns></returns>
        public NCResult SignRead(string yhzh, long queueID)
        {
            string PostUrl = NCConfig.ApiUrl + "/NotifyCenter/SignRead";
            string userID = System.Web.HttpUtility.UrlEncode(yhzh);
            string queueIDStr = System.Web.HttpUtility.UrlEncode(queueID.ToString());
            string postStrTpl = "userID={0}&queueID={1}";
            string paraurl = string.Format(postStrTpl, userID, queueIDStr);
            return this.Post(PostUrl, paraurl);
        }

        private NCResult Post(string postUrl, string paramersStr)
        {
            try
            {
                UTF8Encoding encoding = new UTF8Encoding();
                byte[] postData = encoding.GetBytes(paramersStr);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(postUrl);
                myRequest.Method = "POST";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.ContentLength = postData.Length;

                using (Stream newStream = myRequest.GetRequestStream())
                {
                    newStream.Write(postData, 0, postData.Length);
                    newStream.Flush();
                    newStream.Close();
                }
                string content = "";
                using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
                {
                    StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                    content = reader.ReadToEnd();
                    reader.Close();
                }

                ServerResult sr = JsonConvert.DeserializeObject<ServerResult>(content);
                return new NCResult { code = sr.code, msg = sr.msg, response = sr.response, total = sr.total };
            }
            catch
            {
                return new NCResult { code = -1, msg = "内部服务器错误" };
            }
        }

        /// <summary>
        /// 解析消息参数
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private string GetParameters(Dictionary<string, string> parameters)
        {
            if (parameters != null)
            {
                return JsonConvert.SerializeObject(parameters);
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 解析消息发送目标
        /// </summary>
        /// <param name="customerInfo"></param>
        /// <returns></returns>
        private string GetCustomerInfo(NCCustomerInfo customerInfo)
        {
            if (customerInfo != null)
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                if (!string.IsNullOrWhiteSpace(customerInfo.MobileLink))
                {
                    dic.Add("mobile", customerInfo.MobileLink);
                }
                if (!string.IsNullOrWhiteSpace(customerInfo.EmailLink))
                {
                    dic.Add("email", customerInfo.EmailLink);
                }
                if (!string.IsNullOrWhiteSpace(customerInfo.QQLink))
                {
                    dic.Add("qq", customerInfo.QQLink);
                }
                if (customerInfo.PhonePushLink != null)
                {
                    Dictionary<string, object> dicLink = new Dictionary<string, object>();
                    dicLink.Add("PhoneType", customerInfo.PhonePushLink.DeviceType);
                    dicLink.Add("AppInfo", customerInfo.PhonePushLink.AppInfo);
                    dicLink.Add("CutomerType", customerInfo.PhonePushLink.CutomerType);
                    string phonePushLinkStr = JsonConvert.SerializeObject(dicLink);
                 //   phonePushLinkStr = "{\"PhoneType\":\"" + customerInfo.PhonePushLink.DeviceType + "\",\"AppInfo\":\"" + customerInfo.PhonePushLink.AppInfo + "\",\"CutomerType\":\"" + customerInfo.PhonePushLink.CutomerType + "\"}";
                    dic.Add("phonepush", phonePushLinkStr);
                }

                return JsonConvert.SerializeObject(dic);
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 解析消息发送目标
        /// </summary>
        /// <param name="customerInfo"></param>
        /// <returns></returns>
        private string GetCustomerInfos(List<NCCustomerInfo> customerInfos)
        {
            if (customerInfos != null && customerInfos.Count>0)
            {

                List<Dictionary<string, string>> dics = new List<Dictionary<string, string>>();
                foreach (var customerInfo in customerInfos)
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    if (!string.IsNullOrWhiteSpace(customerInfo.MobileLink))
                    {
                        dic.Add("mobile", customerInfo.MobileLink);
                    }
                    if (!string.IsNullOrWhiteSpace(customerInfo.EmailLink))
                    {
                        dic.Add("email", customerInfo.EmailLink);
                    }
                    if (!string.IsNullOrWhiteSpace(customerInfo.QQLink))
                    {
                        dic.Add("qq", customerInfo.QQLink);
                    }
                    string phonePushLinkStr = "";
                    if (customerInfo.PhonePushLink != null)
                    {
                        phonePushLinkStr = "{\"PhoneType\":\"" + customerInfo.PhonePushLink.DeviceType + "\",\"AppInfo\":\"" + customerInfo.PhonePushLink.AppInfo + "\",\"CutomerType\":\"" + customerInfo.PhonePushLink.CutomerType + "\"}";
                        dic.Add("phonepush", phonePushLinkStr);
                    }
                    dics.Add(dic);
                }

                return JsonConvert.SerializeObject(dics);
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 异步发送信息
        /// </summary>
        /// <param name="templateNo">模板编号</param>
        /// <param name="parameters">参数</param>
        /// <param name="customerInfo">客户联系信息</param>
        /// <returns></returns>
        public NCResult SendMessageAsync(string templateNo, Dictionary<string, string> parameters, NCCustomerInfo customerInfo, string yhzh)
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    SendMessage(templateNo, parameters, customerInfo, yhzh);
                });
            return new NCResult { code = 1 };
        }


        public NCResult SMSBalance(int mobileSendType)
        {
            string PostUrl = NCConfig.ApiUrl + "/NotifyCenter/SMSBalance";
            string postStrTpl = "mobileSendType={0}";
            string paraurl = string.Format(postStrTpl, mobileSendType);
            return this.Post(PostUrl, paraurl);
        }
    }
}
